//
//  GTMianChatListVC.m
//  globalTranslate
//
//  Created by 陈镇 on 2025/8/7.
//

#import "GTMianChatListVC.h"
#import "SLRTheNavigationView.h"
#import "CZMainTabbarView.h"
#import "LHSelectPhotoManager.h"
#import "CZTranslateTableViewCell.h"
#import "CZSelectFontSizeCell.h"
#import "LanguageSelectView.h"
#import "CZInputTextView.h"
#import "WangYiReqManager.h"
#import "CZLocalText.h"
#import "InputVoiceView.h"
#import "GTUserCenterVC.h"
#import "SLUserInfoModel.h"
#import "CZLoadingCell.h"
#import "GTUserCenterVC.h"
#import "CZSelectPhotoOrCrmera.h"


@interface GTMianChatListVC ()<CZMainTabbarViewDelegate,LanguageSelectViewDelegate,QMUIKeyboardManagerDelegate,CZInputTextViewDelegate,InputVoiceViewDelegate>

@property(nonatomic,strong) SLRTheNavigationView *navView;
@property(nonatomic,strong) LanguageSelectView *changeView;
@property(nonatomic,strong) CZMainTabbarView *tabbarView;
@property(nonatomic,strong) CZInputTextView *inputTextView;

@property(nonatomic,strong) CZSelectPhotoOrCrmera *photoOrCrmera;

@property(nonatomic,strong) InputVoiceView *inputVoice;


@property(nonatomic,strong) GTUserCenterVC *myCenter;

@property(nonatomic,strong) QMUIKeyboardManager *keyBoardManager;

@property(nonatomic,strong) NSMutableArray *dataSource;

@end
@implementation GTMianChatListVC

-(void)viewDidLoad{
    [super viewDidLoad];
    
    self.lh_navigationHidden = YES;
    self.tableView.backgroundColor = UIColorWhite;
    self.view.backgroundColor = UIColorWhite;
    
    
    
    [self createData];
  
    
    [self.view addSubview:self.myCenter.view];
    
    [self.view addSubview:self.navView];
    [self.view addSubview:self.tabbarView];
    [self.view addSubview:self.inputTextView];
    
    [self.view addSubview:self.inputVoice];
    [self.view addSubview:self.photoOrCrmera];
    [_inputVoice btnToView:self.view];
    [_inputVoice hiddenbuttom:YES];
    
    self.keyBoardManager = [[QMUIKeyboardManager alloc] initWithDelegate:self];
    
    self.tableView.sectionHeaderTopPadding = 20;
    
    @weakify(self)
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        @strongify(self)
        [self.tableView reloadData];
        [self scrollToBottom];
    });
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeItemType:) name:@"ChangeTranslateType" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeSiztFont) name:@"changeSiztFont" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changTranslateLanguage:) name:@"ChangTranslateLanguage" object:nil];
}

-(void)createData{
    self.dataSource = [NSMutableArray array];
    
    NSArray *localList = [NSArray yy_modelArrayWithClass:[CZTranslateModel class]  json:[CZLocalText localText]];
    [self.dataSource addObjectsFromArray:localList];
   
    
    NSArray *list = (NSArray *)[[WangYiReqManager shareMangager].globalCache objectForKey:kTranslateList];
    
    NSArray *localList2 = [NSArray yy_modelArrayWithClass:[CZTranslateModel class]  json:list];
    [self.dataSource addObjectsFromArray:localList2];
    
}

#pragma mark - 设置UI
-(void)layoutTableView{
    
    if (self.inputTextView.hidden == NO) {
        self.tableView.frame = CGRectMake(0, self.navView.bottom, SCREEN_WIDTH, self.inputTextView.top - self.navView.bottom);
    }else if (self.inputVoice.hidden == NO){
        self.tableView.frame = CGRectMake(0, self.navView.bottom, SCREEN_WIDTH, self.tabbarView.top - self.navView.bottom - 100);
    }else if (self.photoOrCrmera.hidden == NO){
        self.tableView.frame = CGRectMake(0, self.navView.bottom, SCREEN_WIDTH, self.photoOrCrmera.top - self.navView.bottom );
    }else if (self.myCenter.view.hidden == NO){
        self.tableView.frame = CGRectMake(0, self.navView.bottom, SCREEN_WIDTH, self.tabbarView.top - self.navView.bottom );
    }
    
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    CZTranslateModel *model = self.dataSource[indexPath.row];
    
    if (model.cellType == CZTranslateBaseCellType_text) {
        CZTranslateTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CZTranslateTableViewCell"];
        if (!cell) {
            cell = [[CZTranslateTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CZTranslateTableViewCell"];
        }
        cell.model = model;
        return cell;
    }else if (model.cellType == CZTranslateBaseCellType_font){
        CZSelectFontSizeCell*cell = [tableView dequeueReusableCellWithIdentifier:@"CZSelectFontSizeCell"];
        if (!cell) {
            cell = [[CZSelectFontSizeCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CZSelectFontSizeCell"];
        }
        cell.model = model;
        return cell;
    }else if (model.cellType == CZTranslateBaseCellType_loading){
        CZLoadingCell*cell = [tableView dequeueReusableCellWithIdentifier:@"CZLoadingCell"];
        if (!cell) {
            cell = [[CZLoadingCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CZLoadingCell"];
        }
        cell.model = model;
        return cell;
    }{
        return nil;
    }

}
-(SLRTheNavigationView *)navView{
    if (!_navView) {
        _navView = [[SLRTheNavigationView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, NavigationContentTop +44)];
        _navView.bgColor = UIColor.whiteColor;
        _navView.titleLabel.text = @"全球翻译官";
        _navView.titleLabel.font = SLFontMakeMedium(18);
        
        _changeView = [[LanguageSelectView alloc] init];
        _changeView.delegate = self;
        _changeView.type = @"voice";
        _changeView.frame = CGRectMake(MYDistance(100), _navView.height - 55, _navView.width-MYDistance(200), 55);
        [_navView addSubview:_changeView];
        
        
        UIImage *login = [[UIImage imageNamed:@"appusericon"] qmui_imageResizedInLimitedSize:CGSizeMake(32, 32)];
        _navView.rightButtonImage = login;
        _navView.rightButton.userInteractionEnabled = NO;
        [_navView sl_cornerRadius:4];
        
    }
    return _navView;
}


-(CZMainTabbarView *)tabbarView{
    if (!_tabbarView) {
        _tabbarView = [[CZMainTabbarView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - TabBarHeight, SCREEN_WIDTH, TabBarHeight)];
        _tabbarView.delegate = self;
    }
    return _tabbarView;
}
-(CZInputTextView *)inputTextView{
    if (!_inputTextView) {
        _inputTextView = [[CZInputTextView alloc] initWithFrame:CGRectMake(0, self.tabbarView.top - 200, self.view.width, 200)];
        _inputTextView.delegate = self;
    }
    return _inputTextView;
}
-(InputVoiceView *)inputVoice{
    if(!_inputVoice){
        _inputVoice = [[InputVoiceView alloc] initWithFrame:CGRectMake(0, self.view.height - 300 - TabBarHeight , SCREEN_WIDTH, 300)];
        _inputVoice.delegate = self;
        
    }
    return _inputVoice;
}
-(GTUserCenterVC *)myCenter{
    if (!_myCenter) {
        _myCenter = [[GTUserCenterVC alloc] init];
        _myCenter.view.hidden = YES;
    }
    return _myCenter;
}
-(CZSelectPhotoOrCrmera *)photoOrCrmera{
    if (!_photoOrCrmera) {
        _photoOrCrmera = [[CZSelectPhotoOrCrmera alloc] initWithFrame:CGRectMake(0, _tabbarView.top - 44 - 20, self.view.width, 44)];
        _photoOrCrmera.hidden = YES;
        
        [_photoOrCrmera.leftBtn addTarget:self action:@selector(clickPhotoOrCrmera:) forControlEvents:UIControlEventTouchUpInside];
        [_photoOrCrmera.rightBtn addTarget:self action:@selector(clickPhotoOrCrmera:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _photoOrCrmera;
}
#pragma mark - LanguageSelectViewDelegate
-(void)selector_code:(NSString *)or_code ta_code:(NSString *)ta_code{
    
    
    
}
#pragma mark - Notofication
-(void)changeItemType:(NSNotification *)noti{
    NSInteger index = [noti.object integerValue];
    [self mainTabbarViewClickItemWithIndex:index];
    [self.tabbarView selectToIndex:index];
}
-(void)changeSiztFont{
    [self.tableView reloadData];
}

-(void)changTranslateLanguage:(NSNotification *)noti{
    CZTranslateModel *tmpModel = noti.object;
    
   NSInteger index =  [self.dataSource indexOfObject:tmpModel];
    
    __weak typeof(self) weakSelf = self;
    [[WangYiReqManager shareMangager] requestPostfrom:tmpModel.or_code to:tmpModel.ta_code query:tmpModel.orString callBack:^(SLBaseRequest * _Nullable request, id  _Nullable data) {
        RTLog(@"data ------ %@",data);
        if (data) {
            
            CZTranslateModel *model = [CZTranslateModel yy_modelWithJSON:data];
            model.or_code = self.changeView.or_code;
            model.ta_code = self.changeView.ta_code;
            model.isChinese = tmpModel.isChinese;
            model.cellType = CZTranslateBaseCellType_text;
            
            weakSelf.dataSource[index] = model;
            [weakSelf.tableView reloadData];
            [weakSelf scrollToBottom];
        }
    }];
    
    
}
#pragma mark - CZMainTabbarViewDelegate
-(void)mainTabbarViewClickItemWithIndex:(NSInteger)index{
    __weak typeof(self) weakSelf = self;
    switch (index) {
        case 0:{//文字
            _changeView.hidden = NO;
            
            _inputTextView.hidden = NO;
            [_inputVoice hiddenbuttom:YES];
            _photoOrCrmera.hidden = YES;
            _myCenter.view.hidden = YES;
            
       
            break;
        }
        case 1:{//语音
            _changeView.hidden = YES;
            
          
            _inputTextView.hidden = YES;
            [_inputVoice hiddenbuttom:NO];
            _photoOrCrmera.hidden = YES;
            _myCenter.view.hidden = YES;
            break;
        }
        case 2:{//相机 - 相册
    
            _changeView.hidden = NO;
            _inputTextView.hidden = YES;
            [_inputVoice hiddenbuttom:YES];
            _photoOrCrmera.hidden = NO;
            _myCenter.view.hidden = YES;
            
        
     
            break;
        }
        case 3:{//我的
         
            _changeView.hidden = YES;
            
            _inputTextView.hidden = YES;
            [_inputVoice hiddenbuttom:YES];
            _photoOrCrmera.hidden = YES;
            _myCenter.view.hidden = NO;
         
            break;
        }
        default:
            break;
    }
    _navView.height = _changeView.hidden?NavigationContentTop:(NavigationContentTop + _changeView.height);
    [self layoutTableView];
}


-(void)clickPhotoOrCrmera:(QMUIButton *)btn{
    __weak typeof(self) weakSelf = self;
    if (btn == _photoOrCrmera.leftBtn) {//相册


        [LHSelectPhotoManager openPhotoCount:1 block:^(NSArray<UIImage *> * _Nonnull images) {
            [weakSelf requestTranslateImage:images.firstObject];
        }];
        
    }else{//相机
        [LHSelectPhotoManager openCamerBlock:^(NSArray<UIImage *> * _Nonnull images) {
            [weakSelf requestTranslateImage:images.firstObject];
        }];
        
    }
}

-(BOOL)shouldHideKeyboardWhenTouchInView:(UIView *)view{
    if ([view isKindOfClass:[QMUIButton class]]) {
        return NO;
    }
    return YES;
}
#pragma  mark - QMUIKeyboardManagerDelegate
- (void)keyboardWillChangeFrameWithUserInfo:(QMUIKeyboardUserInfo *)keyboardUserInfo
{
    
    CGFloat top = keyboardUserInfo.endFrame.origin.y - self.inputTextView.height;
    if (keyboardUserInfo.endFrame.origin.y > SCREEN_HEIGHT - self.tabbarView.height - self.inputTextView.height) {
        top = SCREEN_HEIGHT - self.tabbarView.height - self.inputTextView.height;
    }
    RTLog(@"%f -- ",top);
    self.inputTextView.top = top;
    [self layoutTableView];
    [self scrollToBottom];
    
}



-(void)scrollToBottom{
    if(self.dataSource.count >0){
        [self.tableView scrollToRow:self.dataSource.count - 1 inSection:0 atScrollPosition:UITableViewScrollPositionNone animated:NO];
    }
}

#pragma mark - CZInputTextViewDelegate

-(void)inputTextViewReturn:(NSString *)text{
    [self requestTranslateText:text];
}

#pragma mark - InputVoiceViewDelegate
-(void)translateCompleteDataVoiceBase64:(NSString *)voiceBase64 isLeft:(BOOL)isLeft{
    
    
    NSString *from =  self.inputVoice.or_code;
    NSString *to =  self.inputVoice.ta_code;
    if (!isLeft) {
        from =  self.inputVoice.ta_code;
        to =  self.inputVoice.or_code;
    }
    
    CZTranslateModel *load = [[CZTranslateModel alloc] init];
    load.isChinese = isLeft;
    load.cellType = CZTranslateBaseCellType_loading;
    load.cell_id = [NSDate date].timeIntervalSince1970 *1000;
    [self.dataSource addObject:load];
    [self.tableView reloadData];
    [self scrollToBottom];
    
    __weak typeof(self) weakSelf = self;
    [[WangYiReqManager shareMangager] requesVoicePostfrom:from to:to query:voiceBase64 callBack:^(SLBaseRequest * _Nullable request, id  _Nullable data) {
        
        
        RTLog(@"data ------ %@",data);
        CZTranslateModel *model = [CZTranslateModel yy_modelWithJSON:data];
        model.isChinese = isLeft;
        model.cellType = CZTranslateBaseCellType_text;
        model.or_code = self.changeView.or_code;
        model.ta_code = self.changeView.ta_code;
        
    
        NSInteger index = [weakSelf.dataSource indexOfObject:load];
        weakSelf.dataSource[index]= model;

        [weakSelf.tableView reloadData];
        [weakSelf scrollToBottom];
        
        [[WangYiReqManager shareMangager].globalCache sl_setObject:model.yy_modelToJSONObject inArrayForKey:kTranslateList];
    }];
}
#pragma mark - 文本翻译
-(void)requestTranslateText:(NSString *)text{
    
    __weak typeof(self) weakSelf = self;
    [[WangYiReqManager shareMangager] requestPostfrom:self.changeView.or_code to:self.changeView.ta_code query:text callBack:^(SLBaseRequest * _Nullable request, id  _Nullable data) {
        RTLog(@"data ------ %@",data);
        if (data) {
            
            CZTranslateModel *model = [CZTranslateModel yy_modelWithJSON:data];
            model.or_code = self.changeView.or_code;
            model.ta_code = self.changeView.ta_code;
            model.cellType = CZTranslateBaseCellType_text;
            [weakSelf.dataSource addObject:model];
            [weakSelf.tableView reloadData];
            [weakSelf scrollToBottom];
            
            [[WangYiReqManager shareMangager].globalCache sl_setObject:model.yy_modelToJSONObject inArrayForKey:kTranslateList];
            
        }
        
    }];
    
    
}
#pragma mark - 图片翻译
-(void)requestTranslateImage:(UIImage *)image{
    
    __weak typeof(self) weakSelf = self;
    
    CZTranslateModel *load = [[CZTranslateModel alloc] init];
    load.cellType = CZTranslateBaseCellType_loading;
    load.cell_id = [NSDate date].timeIntervalSince1970 *1000;
    [self.dataSource addObject:load];
    [self.tableView reloadData];
    [self scrollToBottom];
    
    NSString *imageBase64 = UIImageJPEGRepresentation(image, 0.5).base64EncodedString;
    //UIImagePNGRepresentation(image).base64EncodedString;
    
    [[WangYiReqManager shareMangager] requesImagetPostfrom:self.changeView.or_code to:self.changeView.ta_code query:imageBase64 callBack:^(SLBaseRequest * _Nullable request, id  _Nullable data) {
        RTLog(@"data ------ %@",data);
        if (data) {
            
            CZTranslateModel *model = [CZTranslateModel yy_modelWithJSON:data];
            model.or_code = self.changeView.or_code;
            model.ta_code = self.changeView.ta_code;
            model.cellType = CZTranslateBaseCellType_text;
          
            NSInteger index = [weakSelf.dataSource indexOfObject:load];
            weakSelf.dataSource[index]= model;
            
            [weakSelf.tableView reloadData];
            [weakSelf scrollToBottom];
            
            [[WangYiReqManager shareMangager].globalCache sl_setObject:model.yy_modelToJSONObject inArrayForKey:kTranslateList];
        }
        
    }];
    
}




@end
